Dispatchers should not be hardcoded when using withContext
or creating new coroutines using launch
or async
.
Injectable dispatchers ease testing by allowing tests to inject more deterministic dispatchers.
You can use default values for the dispatcher constructor arguments to eliminate the need to specify them explicitly in the production caller
contexts.
This rule raises an issue when it finds a hard-coded dispatcher being used in withContext
or when starting new coroutines.
Noncompliant code example
class ExampleClass {
suspend fun doSomething() {
withContext(Dispatchers.Default) { // Noncompliant: hard-coded dispatcher
...
}
}
}
Compliant solution
class ExampleClass(
private val dispatcher: CoroutineDispatcher = Dispatchers.Default
) {
suspend fun doSomething() {
withContext(dispatcher) {
...
}
}
}